package cuckoo.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cuckoo.ioc.annotation.Resource;

public class ClassUtil {
	public static Class<?> getClass(String className) {
		try {
			return Class.forName(className);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Class<?> getClassAsResource(String className) {
		Class<?> clazz = getClass(className);
		if (clazz == null)
			return null;

		return isResource(clazz) ? clazz : null;
	}

	public static boolean isResource(Class<?> clazz) {
		boolean isResource = false;
		Annotation[] annotations = clazz.getAnnotations();
		for (Annotation anno : annotations) {
			Class<? extends Annotation> type = anno.annotationType();
			if (type == Resource.class || type.isAnnotationPresent(Resource.class)) {
				isResource = true;
				break;
			}
		}
		return isResource;
	}

	public static Object instance(Class<?> clazz) {
		try {
			return clazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static List<Field> getFieldsByAnno(Class<?> clazz, Class<? extends Annotation> anno) {
		List<Field> list = new ArrayList<Field>();
		Field[] fields = clazz.getDeclaredFields();
		for (Field f : fields) {
			if (f.isAnnotationPresent(anno)) {
				list.add(f);
			}
		}
		return list;
	}

	public static void setFieldValue(Field f, Object target, Object value) {
		try {
			f.setAccessible(true);
			f.set(target, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String invokeMethod(Object obj, String method) {
		try {
			return (String) obj.getClass().getMethod(method).invoke(obj);
		} catch (Exception e) {
			return null;
		}
	}
}
